Page({
  data: {
    messages: [],
    inputMsg: '',
    scrollTop: 0,
    connected: false
  },

  onLoad() {
    this.connectWebSocket();
  },

  connectWebSocket() {
    const socket = wx.connectSocket({
      url: 'ws://localhost:3000'
    });

    socket.onOpen(() => {
      this.setData({ connected: true });
      console.log('WebSocket连接成功');
    });

    socket.onMessage((res) => {
      this.pushMessage('ai', res.data);
    });

    socket.onClose(() => {
      this.setData({ connected: false });
      console.log('WebSocket已断开');
    });

    socket.onError((err) => {
      console.error('WebSocket错误:', err);
      wx.showToast({ title: '连接失败', icon: 'none' });
    });

    this.socket = socket;
  },

  onInput(e) {
    this.setData({ inputMsg: e.detail.value });
  },

  sendMessage() {
    const msg = this.data.inputMsg.trim();
    if (!msg) return;

    this.pushMessage('user', msg);
    this.socket.send({ data: msg });
    this.setData({ inputMsg: '' });
  },

  pushMessage(role, content) {
    const newMsg = { role, content };
    this.setData({
      messages: [...this.data.messages, newMsg],
      scrollTop: this.data.scrollTop + 1000
    });
  }
});
